package workers

import (
	"black_mamba/global"
	"black_mamba/utils"
	"fmt"
	"gitee.com/wengo/go-amazon"
	"gitee.com/wengo/go-mamba"
	"github.com/PuerkitoBio/goquery"
	"io/ioutil"
	"strings"
	"time"
)

type CheckerWorker struct {
	Worker
}

func NewCheckerWorker() *CheckerWorker {
	return &CheckerWorker{
		Worker{
			Topic: "account_checker",
		},
	}
}

func (d *CheckerWorker) Execute(data map[string]interface{}) (ret interface{}) {
	/*
		   流程
		    1.访问首页
			2.新建收货地址，新建信用卡
			3.打开Listing
			4.加入购物车
			5.结账
			6.选择地址
			7.选择信用卡
			8.建立订单
	*/

	//defer func() {
	//	//可以打印错误信息
	//	//recover()
	//	//fmt.Println(recover())
	//
	//	//没有错就不要打印
	//	if err := recover(); err != nil { //产生了panic异常
	//		stackStr := string(debug.Stack())
	//		utils.WriteFile("error.log", fmt.Sprintf("%s\n%s\n", err, stackStr))
	//	}
	//}()

	var resp *mamba.Response
	var document *goquery.Document
	var err error

	//website := `na.account.amazon.com`
	website := `www.amazon.com`
	amz := amazon.NewAmazon(amazon.Settings{
		//JA3:       "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0",
		//UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
		//JA3: "771,4865-4867-4866-49195-49199-52393-52392-49196-49200-49162-49161-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-51-43-13-45-28,,",
		//UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0",
		JA3:       "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0",
		UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36",
		BaseUri:   fmt.Sprintf("https://%s", website),
		//BaseUri:     "https://www.amazon.com",
		Header:      nil,
		Cookies:     nil,
		Debug:       true,
		DebugLength: 0,
		//Proxy:       fmt.Sprintf("http://%s:%s@tunnel5.qg.net:12172", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
		//Proxy:       `http://192.168.2.5:8080`,
		//Proxy: `http://FE6FC783:E0C53AF2F7CD@183.164.247.14:38091`,
		//Proxy: `http://lum-customer-c_17e58ad2-zone-residential:Jjyylu102697@zproxy.lum-superproxy.io:22225`,
		//Proxy: `http://lum-customer-c_17e58ad2-zone-residential-country-ad:Jjyylu102697@zproxy.lum-superproxy.io:22225`,
		//Proxy: `http://lum-customer-c_17e58ad2-zone-residential:Jjyylu102697@47.90.188.193:24001`,
		Proxy: fmt.Sprintf("http://%s:%s@tunnel5.qg.net:14295", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
		//Proxy: fmt.Sprintf("http://%s:%s@http-dynamic.xiaoxiangdaili.com:10030", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
	})

	//isExecute := data["isExecute"].(*bool)
	var responsePath, responseUrl string

	registerUser := data["registerUser"].(*utils.RegisterAccount)

	d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": fmt.Sprintf("邮箱地址 -> %s", registerUser.Email)})
	d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": fmt.Sprintf("用户密码 -> %s", registerUser.Password)})

	continueExecute := true
	for continueExecute {
		//if !*isExecute { //是否继续执行
		//	return
		//}

		switch {
		case resp == nil: // 首页
			d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "打开首页"})
			resp, document, err = amz.Navigate("/")
			if err != nil {
				d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": err.Error()})
				continueExecute = false
			}

			amz.Navigate(fmt.Sprintf("/portal-migration/hz/glow/get-rendered-toaster?pageType=Gateway&aisTransitionState=in&rancorLocationSource=REALM_DEFAULT&_=%d", time.Now()))

		case responsePath == "/" && !strings.Contains(responseUrl, "new_account"):
			//d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "提取登陆链接"})
			loginUrl, err := amz.ExtractLoginUrl(document)
			if err != nil {
				d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": err.Error()})
				continueExecute = false
			}

			resp, document, err = amz.Navigate(loginUrl)
		case responsePath == "/" && strings.Contains(responseUrl, "new_account"):
			d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "进入我的账户"})
			resp, document, err = amz.Navigate(`/gp/css/homepage.html`)
			if err != nil {
				d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": err.Error()})
				continueExecute = false
			}
		case responsePath == "/gp/css/homepage.html":
			link, exists := amz.ExtractSecurityUrl(document)
			if !exists {
				d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": "无法提取账户安全链接"})
				continueExecute = false
			} else {
				d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "进入账户安全设置"})
				resp, document, err = amz.Navigate(link)
			}
		case responsePath == "/ap/signin": //登录
			//amz.Navigate(`/dp/B09TWM7ZKB`)
			//amz.Navigate(`/dp/B09TWM7ZKB`)
			errMsg := amz.CheckLoginError(document)
			if errMsg != "" {
				d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": strings.TrimSpace(errMsg)})
				continueExecute = false
			} else {
				result := amz.CheckLoginInput(document)
				metadata1 := utils.Encrypt([]byte(utils.GeneratedMetadata1()))
				switch result {
				case "email":
					d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "输入邮箱地址"})

					resp, document, err = amz.InputEmail(registerUser.Email, metadata1, document)
				case "password":
					d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "输入密码"})
					resp, document, err = amz.InputPassword(registerUser.Password, metadata1, document)
				}
				//d.sendLog(map[string]string{"status": "info", "email": registerUser.Email, "content": "开始登录"})
				//resp, document, err = amz.Login(registerUser.Email, registerUser.Password, document)
				if err != nil {
					d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": err.Error()})
					continueExecute = false
				}
				ioutil.WriteFile("login.html", resp.Body(), 0644)
			}

		default:
			d.sendLog(map[string]string{"status": "error", "email": registerUser.Email, "content": fmt.Sprintf("未知内容, 退出, 当前页面: %s", responseUrl)})
			ioutil.WriteFile("unknown.html", resp.Body(), 0644)
			continueExecute = false
		}

		if resp != nil {
			responsePath = resp.RawResponse.Request.URL.Path
			responseUrl = resp.RawResponse.Request.URL.String()
		}
	}

	global.BM_EVENTBUS.Publish("register:deleteData", registerUser.Email)

	var statistic map[string]string
	//total := utils.ArrayCountValues(accountStatistic[registerUser.Email]["success"].([]interface{}))
	//global.BM_EVENTBUS.Publish("deals:feedback", total)
	//
	//statisticFormat := fmt.Sprintf("\n 邮箱    : %s\t\n 邮编    : %s\n 收货地址: %s\n 信用卡号: %s\n asins:   %s\n 订单总数: %d\n 订单列表: %s\n===========================================",
	//	registerUser.Email,
	//	accountStatistic[registerUser.Email]["zipCode"],
	//	accountStatistic[registerUser.Email]["address"],
	//	accountStatistic[registerUser.Email]["cc"],
	//	strings.Join(utils.RemoveDuplicateStr(accountStatistic[registerUser.Email]["asins"].([]string)), "\t"),
	//	len(accountStatistic[registerUser.Email]["orders"].([]string)),
	//	strings.Join(accountStatistic[registerUser.Email]["orders"].([]string), "\t"),
	//)
	//
	//statistic = map[string]string{"status": "info", "content": statisticFormat}

	return statistic
}
